import { topList } from '@/api/recommend.js'
import { setItem, getItem } from '@/utils/storage'

const state = {
  topListData: [], // 简易榜单
  hotTopList: [], // 有音乐的榜单
  playMusicList: getItem('NETEASE_MUSICLIST') || [], // 播放页面的音乐列表
  playMusicIndex: getItem('NETEASE_MUSICINDEX') || 0, // 播放到列表中的哪一项
  currentItem: getItem('NETEASE_CURRENTITEM') || {
    name: '无',
    artName: '无',
    picUrl: '',
    mid: '',
    duration: 0
  } // 当前项
}

const mutations = {
  loadTopList (state, payload) {
    state.hotTopList = payload.filter(item => {
      if (item.tracks.length >= 1) {
        return item
      } else {
        state.topListData.push(item)
      }
    })
  },
  // 获取全部
  loadPlayMusicList (state, payload) {
    state.playMusicList = payload
    setItem('NETEASE_MUSICLIST', payload)
  },
  loadPlayMusicIndex (state, payload) {
    state.playMusicIndex = payload
    setItem('NETEASE_MUSICINDEX', payload)
    // 添加当前
    setItem('NETEASE_CURRENTITEM', state.playMusicList[payload])
    state.currentItem = state.playMusicList[payload]
  },
  // 添加一项
  loadPlayMusicItem (state, payload) {
    const result = state.playMusicList.findIndex(item => {
      return item.mid === payload.data.mid
    })
    // 这首歌在播放列表存在就先删除 在提升
    if (result > 0) {
      state.playMusicList.splice(result, 1)
    }
    state.playMusicList.splice(payload.i, 0, payload.data)
    setItem('NETEASE_MUSICLIST', state.playMusicList)
  }
}

const actions = {
  async getTopList (context) {
    const res = await topList()
    context.commit('loadTopList', res.list)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
